
export function startsWith(str, prefix) {  
  if (typeof str !== 'string' || typeof prefix !== 'string') {  
    return false;  
  }  

  if (str.length < prefix.length) {  
    // 如果原字符串长度小于前缀长度，则不可能以该前缀开始  
    return false;  
  }  

  // 逐个字符比较  
  for (let i = 0; i < prefix.length; i++) {  
    if (str[i] !== prefix[i]) {  
      return false;  
    }  
  }  

  // 如果所有字符都匹配，则返回true  
  return true;  
}  

//把JavaScript日期对象 转换成isoString 以便发送到后端
export const formatDate = (date) => {
  const isoString = date.toISOString(); // "2024-06-29T07:04:59.123Z"
  const datePart = isoString.split('.')[0]; // "2024-06-29T07:04:59"
  return datePart;
};

//从后端获取到iso 8601格式的日期字符串 转换成中文的 人看的日期格式 yyyy年mm月dd日
export function formatDateToChinese(isoString) {
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth() is zero-based
  const day = date.getDate().toString().padStart(2, '0');
  
  return `${year}年${month}月${day}日`;
}

//从后端获取到iso 8601格式的日期字符串 转换成中文的 人看的日期格式 xxxx之前
export function timeAgo(dateString) {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;

  const msPerMinute = 60 * 1000;
  const msPerHour = msPerMinute * 60;
  const msPerDay = msPerHour * 24;
  const msPerMonth = msPerDay * 30;

  if (diff < msPerMinute) {
    return '刚刚'; // 刚刚 (less than a minute ago)
  } else if (diff < msPerHour) {
    const minutes = Math.floor(diff / msPerMinute);
    return `${minutes}分钟前`;
  } else if (diff < msPerDay) {
    const hours = Math.floor(diff / msPerHour);
    return `${hours}小时前`;
  } else if (diff < msPerMonth) {
    const days = Math.floor(diff / msPerDay);
    return `${days}天前`;
  } 
}

// // 示例调用
// console.log(timeAgo("2024-06-29T10:00:00")); // 根据当前时间会输出相应的描述



  